package zhang.automobileservice;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import adapter.CarFriendAdapetr;
import bean.CarFriendBean;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.CarServerLoginDB;
import utils.MyUrl;
import utils.PhotoAdapter;
import utils.RecyclerItemClickListener;
import utils.RequestQueueUtils;


public class CarfriendActivity extends FarterActivity implements View.OnClickListener {

    private ImageView iv_carfr;
    private TextView tv_carfr;
    private TextView tv_publish;
    private ImageView iv_write;
    private TextView tv_send;
    private LinearLayout ll_layout;
    private ListView lv_list;
    private RecyclerView rv_addpicture;
    PhotoAdapter photoAdapter;
    ArrayList<String> selectedPhotos = new ArrayList<>();
    private ArrayList<CarFriendBean> arrayList;
    private EditText et_saysth;
    private MyHanler myHanler;

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

    private final OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carfriend);
        initView();
        getData();
        photoAdapter = new PhotoAdapter(this, selectedPhotos);
        rv_addpicture.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        rv_addpicture.setAdapter(photoAdapter);
        rv_addpicture.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                PhotoPicker.builder()
                        .setPhotoCount(9)
                        .setGridColumnCount(4)
                        .start(CarfriendActivity.this);
            }
        }));
        myHanler = new MyHanler();
    }

    private void getData() {
        String url = MyUrl.Font_Url+MyUrl.queryByUser;
        RequestQueueUtils.exectueJsonRequest(getApplicationContext(), url, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject o) {
                arrayList = new ArrayList<CarFriendBean>();
                try {
                    if("0".equals(o.getString("code"))){
                        JSONArray  obj = o.getJSONArray("data");
                        for(int i=0;i<obj.length();i++){
                            JSONObject jsonObject = obj.getJSONObject(i);
                            String username = jsonObject.getString("username");
                            String createDate = jsonObject.getString("createDate");
                            String imgs = jsonObject.getString("imgs");
                            String id = jsonObject.getInt("id")+"";
                            String headPic = jsonObject.getString("headPic");
                            String likeCount = jsonObject.getInt("likeCount")+"";
                            String content = jsonObject.getString("content");
                            CarFriendBean friendBean = new CarFriendBean(id,content,imgs,username,headPic,likeCount,createDate);
                            arrayList.add(friendBean);
                   }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                lv_list.setAdapter(new CarFriendAdapetr(getApplicationContext(),arrayList));
            }
        });
  }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {

                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }


    private void initView() {
        iv_carfr = (ImageView) findViewById(R.id.iv_carfr);
        tv_carfr = (TextView) findViewById(R.id.tv_carfr);
        tv_publish = (TextView) findViewById(R.id.tv_publish);
        iv_write = (ImageView) findViewById(R.id.iv_write);
        tv_send = (TextView) findViewById(R.id.tv_send);
        ll_layout = (LinearLayout) findViewById(R.id.ll_layout);
        lv_list = (ListView) findViewById(R.id.lv_list);
        iv_carfr.setOnClickListener(this);
        iv_write.setOnClickListener(this);
        tv_send.setOnClickListener(this);
        rv_addpicture = (RecyclerView) findViewById(R.id.rv_addpicture);
        rv_addpicture.setOnClickListener(this);
        et_saysth = (EditText) findViewById(R.id.et_saysth);
        et_saysth.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_carfr:
                finish();
                break;
            case R.id.iv_write:
                iv_write.setVisibility(View.INVISIBLE);
                tv_carfr.setVisibility(View.INVISIBLE);
                lv_list.setVisibility(View.INVISIBLE);
                tv_publish.setVisibility(View.VISIBLE);
                tv_send.setVisibility(View.VISIBLE);
                ll_layout.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_send:
                uploadImg();
                break;
        }
    }

    private void uploadImg() {
        String url = MyUrl.Font_Url + MyUrl.addNote;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i <selectedPhotos.size() ; i++) {
            File f=new File(selectedPhotos.get(i));
            if (f!=null) {
                builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        //添加其它信息
        builder.addFormDataPart("userId",getSharedPreferences("TAGtext",MODE_PRIVATE).getString("id", "1"));
        builder.addFormDataPart("content",et_saysth.getText().toString());
        Log.e("----",getSharedPreferences("TAGtext",MODE_PRIVATE).getString("id", "1"));
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)//添加请求体
                .build();;

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("---",e.toString());
                myHanler.sendEmptyMessage(0);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                myHanler.sendEmptyMessage(1);
            }
        });


    }

    class MyHanler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                Toast.makeText(getApplicationContext(),"上传照片失败 ", Toast.LENGTH_LONG).show();
            }else if(msg.what==1){
                Toast.makeText(getApplicationContext(),"上传照片成功 ", Toast.LENGTH_LONG).show();
            }
        }
    }

}
